<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="90px">
      <el-form-item label="学生名字" prop="name">
        <el-input v-model="queryParams.name" placeholder="请输入学生名字" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>

      <el-form-item label="课程名字" prop="courseName">
        <el-input v-model="queryParams.courseName" placeholder="请输入课程名字" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="渠道来源" prop="scource">
        <el-input v-model="queryParams.scource" placeholder="请输入渠道来源" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="课程顾问" prop="counselor">
        <el-input v-model="queryParams.counselor" placeholder="请输入课程顾问" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>

      <el-form-item label="到期时间" prop="dueDate">
        <el-date-picker clearable v-model="queryParams.dueDate" type="datetime" value-format="yyyy-MM-dd HH:mm:ss"
          placeholder="请选择到期时间">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="创建时间" prop="createTime">
        <el-date-picker clearable v-model="queryParams.createTime" type="datetime" value-format="yyyy-MM-dd HH:mm:ss"
          placeholder="请选择创建时间">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="课程教练" prop="coach">
        <el-input v-model="queryParams.coach" placeholder="请输入课程教练" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="学生类型" prop="typeId">
        <el-select v-model="queryParams.typeId" placeholder="请选择学生类型">
          <el-option v-for="item in studentTypes" :key="item.id" :label="item.name" :value="item.id">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="手机号码" prop="phone">
        <el-input v-model="queryParams.phone" placeholder="请输入手机号码" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="身份证号码" prop="idCard">
        <el-input v-model="queryParams.idCard" placeholder="请输入身份证号码" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
          v-hasPermi="['horse:class:add']">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="el-icon-edit" size="mini" :disabled="single" @click="handleUpdate"
          v-hasPermi="['horse:class:edit']">修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete"
          v-hasPermi="['horse:class:remove']">删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport"
          v-hasPermi="['horse:class:export']">导出</el-button>
      </el-col>
      <!-- <el-col :span="1.5">
        <el-button type="warning" plain icon="el-icon-download" size="mini" @click="importExcel"
          v-hasPermi="['horse:class:export']">批量导入</el-button>
      </el-col> -->
      <el-col :span="1.5">
        <el-button type="info" icon="el-icon-upload2" size="mini" @click="handleImport"
          v-hasPermi="['horse:class:import']">批量导入</el-button>
      </el-col>
      
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="classList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
   
      <el-table-column  label="学生名字" width="auto" align="center" prop="name" fixed/>
     
      <el-table-column label="学生类型" align="center" prop="typeId">
        <template slot-scope="scope">
          <el-tag v-if="scope.row.typeId == 0" type="success"> 体验会员</el-tag>
          <el-tag v-if="scope.row.typeId == 1" type="primary"> 正式会员</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="出生年月" align="center" prop="birthday" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.birthday, "{y}-{m}-{d}") }}</span>
        </template>
      </el-table-column>
      <el-table-column label="手机号码" align="center" prop="phone" width="110" />
      <el-table-column label="身份证号码" align="center" prop="idCard" width="180" />
      <el-table-column label="课程名称" align="center" prop="courseName" width="90" />
      <el-table-column label="渠道来源" align="center" prop="scource" width="90" />
      <el-table-column label="课程顾问" align="center" prop="counselor" />
      <el-table-column label="缴费金额" align="center" prop="coursePrice" />
      <el-table-column label="缴费日期" align="center" prop="priceDate" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.priceDate, "{y}-{m}-{d} {h}:{i}:{s}") }}</span>
        </template>
      </el-table-column>
      <el-table-column label="到期时间" align="center" prop="dueDate" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.dueDate, "{y}-{m}-{d}  {h}:{i}:{s}") }}</span>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" align="center" prop="createTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime, "{y}-{m}-{d} {h}:{i}:{s}") }}</span>
        </template>
      </el-table-column>
      <el-table-column label="课程教练" align="center" prop="coach" />

      <el-table-column label="体验课时" align="center" prop="expHour" />
      <el-table-column label="赠送课时" align="center" prop="giftHour" />
      <el-table-column label="购买课时" align="center" prop="buyHour" />
      <el-table-column label="总计课时" align="center" prop="totalHour" />
      <el-table-column label="已消耗课时" align="center" prop="usedHour" width="90" />
      <el-table-column label="剩余课时" align="center" prop="remainHour" />
      <el-table-column label="描述" align="center" prop="note" />
      <el-table-column label="所属校长" align="center" prop="masterName" v-if="checkRole(['common_admin'])" />
      <el-table-column label="所属老师" align="center" prop="teacherName" v-if="checkRole(['common_admin','master'])" />
      <el-table-column label="消课状态" align="center" prop="status">
        <template slot-scope="scope">
          <el-tag type="danger" v-if="scope.row.status == 0">未消课</el-tag>
          <el-tag type="primary" v-if="scope.row.status == 1">已消课</el-tag>
          <!-- <el-tag type="success" v-if="scope.row.status == 2">正在消课</el-tag> -->
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="300px"  >
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-user-solid" @click="handleTime(scope.row)" v-hasPermi="['horse:class:updateCourseHour']">消耗课时</el-button>
          <el-button size="mini" type="text" icon="el-icon-remove" @click="handleRemove(scope.row)" v-hasPermi="['horse:class:doneClass']">销课</el-button>
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"
            v-hasPermi="['horse:class:edit']">修改</el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
            v-hasPermi="['horse:class:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="getList" />
    <!-- 用户导入对话框 -->
    <el-dialog :title="upload.title" :visible.sync="upload.open" width="400px">
      <el-upload ref="upload" :limit="1" accept=".xlsx, .xls" :headers="upload.headers"
        :action="upload.url + '?updateSupport=' + upload.updateSupport" :disabled="upload.isUploading"
        :on-progress="handleFileUploadProgress" :on-success="handleFileSuccess" :auto-upload="false" drag>
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">
          将文件拖到此处，或
          <em>点击上传</em>
        </div>
        <div class="el-upload__tip" slot="tip">
          <el-checkbox v-model="upload.updateSupport" />是否更新已经存在的用户数据
          
          <el-link type="info" style="font-size:12px" @click="importTemplate">下载模板</el-link>
        </div>
        <div class="el-upload__tip" style="color:red" slot="tip">提示：仅允许导入“xls”或“xlsx”格式文件！</div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFileForm">确 定</el-button>
        <el-button @click="upload.open = false">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 添加或修改班级对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="学生名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入学生名称" />
        </el-form-item>
        <el-form-item label="学生类型" prop="typeId">
          <el-select v-model="form.typeId" placeholder="选择学生类型" style="width: 100%" clearable>
            <el-option v-for="item in studentTypes" :label="item.name" :value="item.id" :key="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="课程名字" prop="courseId">
          <el-select v-model="form.courseId" placeholder="请输入归属课程" >
            <el-option v-for="item in courseOption" :key="item.value" :label="item.name" :value="item.id"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="出生年月" prop="birthday">
          <el-date-picker v-model="form.birthday" type="date" style="width: 100%" placeholder="请选择出生时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="手机号码" prop="phone">
          <el-input v-model="form.phone" placeholder="请输入手机号码" />
        </el-form-item>
        <el-form-item label="身份证号码" prop="idCard">
          <el-input v-model="form.idCard" placeholder="请输入身份证号码" />
        </el-form-item>
        
        <el-form-item label="渠道来源" prop="scource">
          <el-input v-model="form.scource" placeholder="请输入渠道来源" />
        </el-form-item>
        <el-form-item label="教练" prop="scource">
          <el-input v-model="form.coach" placeholder="请输入教练" />
        </el-form-item>
        <el-form-item label="课程顾问" prop="counselor">
          <el-input v-model="form.counselor" placeholder="请输入课程顾问"  />
        </el-form-item>
        <el-form-item label="缴费金额" prop="coursePrice">
          <el-input v-model="form.coursePrice" placeholder="请输入缴费金额"  />
        </el-form-item>
        <el-form-item label="缴费日期" prop="priceDate">
          <el-date-picker clearable v-model="form.priceDate" type="datetime" value-format="yyyy-MM-dd HH:mm:ss" placeholder="请选择缴费日期">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="到期时间" prop="dueDate">
          <el-date-picker clearable v-model="form.dueDate" type="datetime" value-format="yyyy-MM-dd HH:mm:ss" placeholder="请选择到期时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="购买课时" prop="buyHour" >
          <el-input v-model="form.buyHour" placeholder="请输入购买课时"  />
        </el-form-item>
        <el-form-item label="体验课时" prop="expHour">
          <el-input v-model="form.expHour" placeholder="请输入体验课时" />
        </el-form-item>
        <el-form-item label="赠送课时" prop="giftHour" >
          <el-input v-model="form.giftHour" placeholder="请输入赠送课时" />
        </el-form-item>
        <!-- <el-form-item label="总计课时" prop="totalHour">
          <el-input v-model="form.totalHour" placeholder="请输入总计课时" :disabled="this.isUpdate"/>
        </el-form-item> -->
        <el-form-item label="已消耗课时" prop="usedHour">
          <el-input v-model="form.usedHour" placeholder="请输入已消耗课时"  />
        </el-form-item>
        <el-form-item label="剩余课时" prop="remainHour">
          <el-input v-model="form.remainHour" placeholder="请输入剩余课时" :disabled="true" />
        </el-form-item>
         <el-form-item label="描述" prop="note">
          <el-input v-model="form.note" placeholder="请输入描述" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>


    <el-dialog title="消耗课时" :visible.sync="timeFormOpen" width="500px">
      <el-form ref="timeForm" :model="timeForm" label-width="80px">
        <el-form-item label="消耗课时" prop="name">
          <el-input-number v-model="timeForm.hour" precision="1" step="0.5" :min="0" :max="10000" label="选择消耗的课时"></el-input-number>
          <!-- <el-input v-model="timeForm.time" placeholder="消耗课时" /> -->
        </el-form-item>

        <el-form-item label="上课教练" prop="coachName">
          <el-input v-model="timeForm.coach" placeholder="输入上课教练" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitTimeForm">确 定</el-button>
        <!-- <el-button @click="this.">取 消</el-button> -->
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listClass,
  getClass,
  delClass,
  addClass,
  updateClass,
  updateCourseHour,
  doneClass,
} from "@/api/horse/class";
import { allCourse } from "@/api/horse/course";
import { getToken } from "@/utils/auth";
import { checkPermi, checkRole } from "@/utils/permission"; // 权限判断函数

export default {
  name: "Class",
  data() {
    return {
      studentTypes: [
        {
          id: 0,
          name: "体验会员",
        },
        {
          id: 1,
          name: "正式会员",
        },
      ],
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 班级表格数据
      classList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        name: null,
      },
      // 用户导入参数
      upload: {
        // 是否显示弹出层（用户导入）
        open: false,
        // 弹出层标题（用户导入）
        title: "",
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的用户数据
        updateSupport: 0,
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/horse/class/importData"
      },


      // 表单参数
      form: {},
      // 表单校验
      rules: {
        name: [
          { required: true, message: "班级名称不能为空", trigger: "blur" },
        ],
      },
      courseOption: [],
      isUpdate: false,
      timeForm: {
        hour: 0,
      },
      timeFormOpen: false,
    };
  },
  created() {
    this.getList();
    this.getCourseOption();
  },
  methods: {
    checkRole,
    handleRemove(row) {
      console.log(row);
      this.$modal
        .confirm('是否确认注销班级名称为"' + row.name + '"的数据项？')
        .then((res) => {
          var data = {
            classId: row.id,
          };
          doneClass(data).then((res) => {
            this.$modal.msgSuccess("销课成功");
            this.getList();
          });
        });
    },
    submitTimeForm() {
      // console.log(this.timeForm)
      updateCourseHour(this.timeForm).then((res) => {
        this.$modal.msgSuccess("修改成功");
        this.timeFormOpen = false;
        this.getList();
      });
    },
    handleTime(row) {
      this.timeForm.classId = row.id;
      this.timeFormOpen = true;
    },
    handleClassStudent(row) {
      this.$router.push({ path: "/classStudent", query: { classId: row.id } });
    },
    getCourseOption() {
      allCourse().then((res) => {
        this.courseOption = res.data;
      });
    },
    /** 查询班级列表 */
    getList() {
      this.loading = true;
      listClass(this.queryParams).then((response) => {
        this.classList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        name: null,
        teacherId: null,
        masterId: null,
        expHour: null,
        scource: null,
        counselor: null,
        coursePrice: null,
        priceDate: null,
        dueDate: null,
        buyHour: null,
        giftHour: null,
        createTime: null,
        updateTime: null,
        totalHour: null,
        usedHour: null,
        remainHour: null,
        coach: null,
        delFlag: null,
        status: null,
        courseId: null,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.id);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加学生";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids;
      getClass(id).then((response) => {
        this.form = response.data;
        this.open = true;
        this.title = "修改学生";
        this.isUpdate = true;
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          if (this.form.id != null) {
            updateClass(this.form).then((response) => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addClass(this.form).then((response) => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal
        .confirm('是否确认删除学生编号为"' + ids + '"的数据项？')
        .then(function () {
          return delClass(ids);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => { });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download(
        "horse/class/export",
        {
          ...this.queryParams,
        },
        `class_${new Date().getTime()}.xlsx`
      );
    },
    /** 导入按钮操作 */
    handleImport() {
      this.upload.title = "批量导入";
      this.upload.open = true;
    },
    /** 下载模板操作 */
    importTemplate() {
      this.download(
        'horse/class/importTemplate',
        {},
        `student_template_${new Date().getTime()}.xlsx`)
    },
    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true;
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      this.upload.open = false;
      this.upload.isUploading = false;
      this.$refs.upload.clearFiles();
      this.$alert(response.msg, "导入结果", { dangerouslyUseHTMLString: true });
      this.getList();
    },
    // 提交上传文件
    submitFileForm() {
      this.$refs.upload.submit();
    }
  }
};
</script>
